<!--
 * @Descripttion: (售后管理主页/EG_Feedback_Main)
 * @Author: (admin)
 * @Date: (2025-11-21)
-->
<template>
  <div>
    <el-form :model="queryParams" label-position="right" inline ref="queryRef" v-show="showSearch" @submit.prevent>
      <el-form-item>
        <el-button icon="search" type="primary" @click="handleQuery">{{ $t('btn.search') }}</el-button>
        <el-button icon="refresh" @click="resetQuery">{{ $t('btn.reset') }}</el-button>
      </el-form-item>
    </el-form>
    <!-- 工具区域 -->
    <el-row :gutter="15" class="mb10">
      <el-col :span="1.5">
        <el-button type="primary" v-hasPermi="['egfeedbackmain:add']" plain icon="plus" @click="handleAdd">
          {{ $t('btn.add') }}
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" v-hasPermi="['egfeedbackmain:send']" plain icon="plus" @click="handleStatus('Y')">
          {{ $t('btn.send') }}
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" v-hasPermi="['egfeedbackmain:back']" plain icon="plus" @click="handleStatus('0')">
          {{ $t('btn.back') }}
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table
      :data="dataList"
      v-loading="loading"
      ref="table"
      border
      header-cell-class-name="el-table-header-cell"
      highlight-current-row
      @sort-change="sortChange"
       @selection-change="handleSelectionChange"
 
      >
      <el-table-column type="selection" width="55" align="center" />
 
      <el-table-column prop="feedbackID" label="编号" align="center" :show-overflow-tooltip="true" v-if="columns.showColumn('feedbackID')"/>
      <el-table-column prop="machineNo" label="机器号" align="center" :show-overflow-tooltip="true" v-if="columns.showColumn('machineNo')"/>
      <el-table-column prop="orderNo" label="订单号" align="center" :show-overflow-tooltip="true" v-if="columns.showColumn('orderNo')"/>
      <el-table-column prop="cusNo" label="客户编号" align="center" :show-overflow-tooltip="true" v-if="columns.showColumn('cusNo')"/>
   
      <el-table-column prop="cusName" label="客户名称" align="center" :show-overflow-tooltip="true" v-if="columns.showColumn('cusName')"/>
       <el-table-column prop="suppNo" label="供应商号" align="center" :show-overflow-tooltip="true" v-if="columns.showColumn('suppNo')"/>
   <el-table-column prop="suppName" label="供应商号" align="center" :show-overflow-tooltip="true" v-if="columns.showColumn('cusName')"/>
 
      <el-table-column prop="shipmentDate" label="发货日期" :formatter="dateFormatter" align="center" v-if="columns.showColumn('shipmentDate')"/>
      <el-table-column prop="factoryDate" label="出厂日期" :formatter="dateFormatter" align="center" v-if="columns.showColumn('factoryDate')"/>
          <el-table-column prop="problemType" label="问题类型" align="center"  v-if="columns.showColumn('problemType')"/>
   
      <el-table-column prop="problemDesc" label="问题描述" align="center" :show-overflow-tooltip="true" v-if="columns.showColumn('problemDesc')"/>
      <el-table-column prop="problemUrl" label="问题附件" align="center" v-if="columns.showColumn('problemUrl')">
        <template #default="scope">
          <ImagePreview :src="scope.row.problemUrl"></ImagePreview>
        </template>
      </el-table-column>
      <el-table-column prop="problemNum" label="相关数量" align="center" v-if="columns.showColumn('problemNum')"/>
      <el-table-column prop="problemComponet" label="问题部件" align="center" :show-overflow-tooltip="true" v-if="columns.showColumn('problemComponet')"/>
      <el-table-column prop="feedbackDate" label="反馈日期" :formatter="dateFormatter" align="center" v-if="columns.showColumn('feedbackDate')"/>
      <el-table-column prop="feedbackName" label="反馈人员" align="center" :show-overflow-tooltip="true" v-if="columns.showColumn('feedbackName')"/>
      <el-table-column prop="createTime" label="创建实际" :show-overflow-tooltip="true"  v-if="columns.showColumn('createTime')"/>
      <el-table-column prop="createName" label="创建人" align="center" :show-overflow-tooltip="true" v-if="columns.showColumn('createName')"/>
        <el-table-column prop="isStaus" label="状态" align="center" :show-overflow-tooltip="true" v-if="columns.showColumn('isStaus')"/>
    
      <el-table-column prop="def" label="备注" align="center" :show-overflow-tooltip="true" v-if="columns.showColumn('def')"/>
       <el-table-column label="操作" width="160">
        <template #default="scope">
          <el-button type="success" size="small" icon="edit" title="编辑" v-hasPermi="['egfeedbackmain:edit']" @click="handleUpdate(scope.row)"></el-button>
          <el-button type="primary" size="small" icon="chat-line-round" title="跟进" @click="handleChat(scope.row.feedbackID)"></el-button>
           <el-button type="danger" size="small" icon="delete" title="删除" v-hasPermi="['egfeedbackmain:delete']" @click="handleDelete(scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />


    <el-dialog :title="title" :lock-scroll="false" v-model="open" width="1200px"  >
      <el-form ref="formRef" :model="form"  label-width="100px">
        <el-row :gutter="20">


          <el-col :lg="6">
            <el-form-item label="机器号" prop="machineNo">
            
                     <el-input v-model="form.machineNo" placeholder="请输入机器号">
                <template #append>
                  <el-button type="primary" @click="SelectMachine" style="width: 60px">
                    获取
                    <el-icon><time /></el-icon>
                  </el-button>
                </template>
              </el-input>
         
            </el-form-item>
          </el-col>

     <el-col :lg="6">
            <el-form-item label="机器型号" prop="ProblemModel">
              <el-input v-model="form.ProblemModel" placeholder="请输入型号"   />
            </el-form-item>
          </el-col>

          <el-col :lg="6">
            <el-form-item label="订单号" prop="orderNo">
              <el-input v-model="form.orderNo" placeholder="请输入订单号"   />
            </el-form-item>
          </el-col>

          <el-col :lg="6">
            <el-form-item label="出厂日期" prop="factoryDate">
                      <el-date-picker
                v-model="form.factoryDate"
                type="date"
                placeholder="选择出厂日期" >
              </el-date-picker>
            
            </el-form-item>
          </el-col>

           <el-col :lg="12">
            <el-form-item label="客户" prop="cusNo">
                 <el-input v-model="form.cusNo" placeholder="点击选择客户" readonly @click="opencusTable" style="width: 20%;" />
                    <el-input v-model="form.cusName" placeholder=""  disabled   style="width: 80%;" />
            </el-form-item>
          </el-col>

          

          <el-col :lg="12" >
            <el-form-item label="供应商" prop="suppNo">
                <el-input v-model="form.suppNo" placeholder="点击选择供应商" readonly @click="opensuppTable" style="width: 20%;"/>
                   <el-input v-model="form.suppName" placeholder="" disabled style="width: 80%;" />
            </el-form-item>
          </el-col>
  
          <el-col :lg="6">
            <el-form-item label="发货日期" prop="shipmentDate">
                   <el-date-picker
                v-model="form.shipmentDate"
                type="date"
                placeholder="选择发货日期" >
              </el-date-picker>
           
              
            </el-form-item>
          </el-col>



       

          <el-col :lg="6">
            <el-form-item label="问题类型" prop="problemType">
              <el-select v-model="form.problemType" clearable   filterable placeholder="请选择问题类型">
                <el-option
                  v-for="item in  problemTypeOptions" 
                  :key="item.dictValue" 
                  :label="item.dictLabel" 
                  :value="item.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
 <el-col :lg="6">
            <el-form-item label="相关数量" prop="problemNum">
              <el-input v-model.number="form.problemNum" placeholder="请输入相关数量" />
            </el-form-item>
          </el-col>

          <el-col :lg="6">
            <el-form-item label="问题部件" prop="problemComponet">
              <el-input v-model="form.problemComponet" placeholder="请输入问题部件" />
            </el-form-item>
          </el-col>

          <el-col :lg="6">
            <el-form-item label="反馈日期" prop="feedbackDate">
                  <el-date-picker
                v-model="form.feedbackDate"
                type="date"
                placeholder="选择反馈日期" >
              </el-date-picker>
           
            </el-form-item>
          </el-col>

          <el-col :lg="6">
            <el-form-item label="反馈人员" prop="feedbackName">
              <el-input v-model="form.feedbackName" placeholder="请输入反馈人员" />
            </el-form-item>
          </el-col>

           

          <el-col :lg="12">
            <el-form-item label="备注" prop="def">
              <el-input v-model="form.def" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
          <el-col :lg="24">
                <!-- <editor v-model="form.problemDesc" :toolbarConfig="toolbarConfig" :min-height="40" /> -->
        <el-form-item label="问题描述" prop="problemDesc">
          <el-input 
            v-model="form.problemDesc" 
            type="textarea" 
            :rows="4" 
            placeholder="请输入问题描述"
          />
        </el-form-item>   
          </el-col>

         
 
          <el-col :lg="24">
            <el-form-item label="图片" prop="problemUrl">
             <UploadImage 
            v-model="form.problemUrl" 
            :data="{ uploadType: 1 }" 
            :limit="10" 
            multiple
          />
            </el-form-item>
          </el-col>
            
        </el-row>
      </el-form>
      <template #footer v-if="opertype != 3">
        <el-button text @click="cancel">{{ $t('btn.cancel') }}</el-button>
        <el-button type="primary" :loading="state.submitLoading" @click="submitForm">{{ $t('btn.submit') }}</el-button>
      </template>
    </el-dialog>
       <SelectMachine-table ref="saleorderRef" @ok="handleSelectMachine" />
       <SelectSupp-table ref="suppRef" @ok="handleSelectSupp" />
       <SelectCus-table ref="cusRef" @ok="handleSelectCus" />
  </div> 
</template>

<script setup name="egfeedbackmain">
import { listEgFeedbackMain,
 addEgFeedbackMain, delEgFeedbackMain, 
  updateEgFeedbackMain, getEgFeedbackMain, 
 listsaleorder, listsupp, listcus
 } 
  from '@/api/buss/egfeedbackmain.js'
import { useRouter } from 'vue-router' 
const router = useRouter()
// 富文本组件
import Editor from '@/components/Editor'
import useUserStore from '@/store/modules/user'
const userInfo = computed(() => {
  return useUserStore().userInfo
})
const { proxy } = getCurrentInstance()
const ids = ref([]) 
import SelectMachineTable from './SelectMachine'
import SelectSuppTable from './SelectSupp'
import SelectCusTable from './SelectCus'
const loading = ref(false)
const showSearch = ref(true)
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  sort: 'FeedbackID',
  sortType: 'asc',
})
// 日期格式化函数
function dateFormatter(row, column, cellValue) {
  if (!cellValue) return ''
  return new Date(cellValue).toISOString().split('T')[0]
}
//富文本
const toolbarConfig = ref({
  toolbarKeys: [
    // 菜单 key
    'headerSelect',
    'bold', // 加粗
    'italic', // 斜体
    'through', // 删除线
    'underline', // 下划线
    'bulletedList', // 无序列表
    'numberedList', // 有序列表
    'color', // 文字颜色
    'uploadImage', // 上传图片
    'delIndent', // 缩进
    'indent', // 增进
    'insertLink', // 插入链接
    'fontSize', // 字体大小
    'clearStyle', // 清除格式
    'divider', // 分割线
    'insertTable', // 插入表格
    'justifyCenter', // 居中对齐
    'justifyJustify', // 两端对齐
    'justifyLeft', // 左对齐
    'justifyRight', // 右对齐
    'emotion',
    'fullScreen' // 全屏
  ]
})

const columns = ref([
  { visible: true, align: 'center', type: '', prop: 'feedbackID', label: '编号'  ,showOverflowTooltip: true  },
  { visible: true, align: 'center', type: '', prop: 'machineNo', label: '机器号'  ,showOverflowTooltip: true  },
  { visible: true, align: 'center', type: '', prop: 'orderNo', label: '订单号'  ,showOverflowTooltip: true  },
  { visible: true, align: 'center', type: 'dict', prop: 'cusNo', label: '客户号'  ,showOverflowTooltip: true  },
  { visible: true, align: 'center', type: '', prop: 'cusName', label: '客户名称'  ,showOverflowTooltip: true  },
  { visible: true, align: 'center', type: 'dict', prop: 'suppNo', label: '供应商号'  ,showOverflowTooltip: true  },
  { visible: true, align: 'center', type: '', prop: 'shipmentDate', label: '发货日期'   },
  { visible: true, align: 'center', type: '', prop: 'factoryDate', label: '出厂日期'   },
  { visible: false, align: 'center', type: '', prop: 'suppName', label: '供应商'  ,showOverflowTooltip: true  },
  { visible: false, align: 'center', type: 'dict', prop: 'problemType', label: '问题类型'  ,showOverflowTooltip: true  },
  { visible: false, align: 'center', type: '', prop: 'problemDesc', label: '问题描述'  ,showOverflowTooltip: true  },
  { visible: false, align: 'center', type: 'img', prop: 'problemUrl', label: '问题附件'  ,showOverflowTooltip: true  },
  { visible: false, align: 'center', type: '', prop: 'problemNum', label: '相关数量'   },
  { visible: false, align: 'center', type: '', prop: 'problemComponet', label: '问题部件'  ,showOverflowTooltip: true  },
  { visible: false, align: 'center', type: '', prop: 'feedbackDate', label: '反馈日期'   },
  { visible: false, align: 'center', type: '', prop: 'feedbackName', label: '反馈人员'  ,showOverflowTooltip: true  },
  { visible: false, align: 'center', type: '', prop: 'createTime', label: 'CreateTime'  ,showOverflowTooltip: true  },
  { visible: false, align: 'center', type: '', prop: 'createName', label: 'CreateName'  ,showOverflowTooltip: true  },
  { visible: false, align: 'center', type: 'dict', prop: 'isStaus', label: '状态'  ,showOverflowTooltip: true  },
  { visible: false, align: 'center', type: '', prop: 'def', label: '备注'  ,showOverflowTooltip: true  },
  { visible: false, align: 'center', type: '', prop: 'sourceFrom', label: '来源'  ,showOverflowTooltip: true  },
  //{ visible: false, prop: 'actions', label: '操作', type: 'slot', width: '160' }
])
const total = ref(0)
const dataList = ref([])
const queryRef = ref()
const defaultTime = ref([new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)])


var dictParams = [
]
function opensaleTable() {
  proxy.$refs['saleorderRef'].show()
}
function opensuppTable() {
  proxy.$refs['suppRef'].show()
}


function opencusTable() {
  proxy.$refs['cusRef'].show()
}
function getList(){
  loading.value = true
  listEgFeedbackMain(queryParams).then(res => {
    const { code, data } = res
    if (code == 200) {
      dataList.value = data.result
      total.value = data.totalNum
      loading.value = false
    }
  })
}

// 查询
function handleQuery() {
  queryParams.pageNum = 1
  getList()
}

// 重置查询操作
function resetQuery(){
  proxy.resetForm("queryRef")
  handleQuery()
}
// 自定义排序
function sortChange(column) {
  var sort = undefined
  var sortType = undefined

  if (column.prop != null && column.order != null) {
    sort = column.prop
    sortType = column.order

  }
  queryParams.sort = sort
  queryParams.sortType = sortType
  handleQuery()
}

/*************** form操作 ***************/
const formRef = ref()
const title = ref('')
// 操作类型 1、add 2、edit 3、view
const opertype = ref(0)
const open = ref(false)
const state = reactive({
  single: true,
  multiple: true,
  submitLoading: false,
  form: {},
  options: {
    // 客户号 选项列表 格式 eg:{ dictLabel: '标签', dictValue: '0'}
problemTypeOptions: [],
  }
})
var  problemTypeOptions = ref([])
const { form,   options, single, multiple } = toRefs(state)

// 关闭dialog
function cancel(){
  open.value = false
  reset()
}

// 重置表单
function reset() {
  form.value = {
    feedbackID: null,
    machineNo: null,
    orderNo: null,
    cusNo: null,
    cusName: null,
    suppNo: null,
    shipmentDate: null,
    factoryDate: null,
    suppName: null,
    problemType: null,
    problemDesc: null,
    problemUrl: null,
    problemNum: null,
    problemComponet: null,
    feedbackDate: formatDate(new Date()),
    feedbackName: userInfo.value.nickName,
    createTime: null,
    createName: null,
    isStaus: '0',
    def: null,
    sourceFrom: 'PC',
  };
  proxy.resetForm("formRef")
}
 function formatDate(date) {
      const yyyy = date.getFullYear();
      const mm = (date.getMonth() + 1).toString().padStart(2, '0'); // 月份是从0开始的
      const dd = date.getDate().toString().padStart(2, '0');
      return `${yyyy}-${mm}-${dd}`;
    }

// 添加按钮操作
function handleAdd() {
  reset();
  open.value = true
  state.submitLoading = false
  title.value = '添加售后管理主页'
  opertype.value = 1
}
// 修改按钮操作
function handleUpdate(row) {
  reset()
  const id = row.feedbackID || ids.value
  getEgFeedbackMain(id).then((res) => {
    const { code, data } = res
    if (code == 200) {
      open.value = true
      title.value = '修改售后管理主页'
      opertype.value = 2

      form.value = {
        ...data,
      }
    }
  })
}

// 添加&修改 表单提交
function submitForm() {
  proxy.$refs["formRef"].validate((valid) => {
    if (valid) {
      state.submitLoading = true 
      if (form.value.feedbackID != undefined) {
        updateEgFeedbackMain(form.value).then((res) => {
             state.submitLoading = false
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
          form.value.feedbackID =   ''
        addEgFeedbackMain(form.value).then((res) => {
             state.submitLoading = false
            proxy.$modal.msgSuccess("新增成功")
            open.value = false
            getList()
          })
          .finally(() => {
            setTimeout(() => {
              state.submitLoading = false
            }, 800)
          })
      }
    }
  })
}
// 处理多选框变化
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.feedbackID);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}// 优化handleStatus函数
function handleStatus(status) {
  // Check if any rows are selected
  if (ids.value.length === 0) {
    proxy.$modal.msgWarning("请先选择要操作的数据项");
    return;
  }

  let statusText = '';
  switch(status) {
    case 'Y':
      statusText = '发送';
      break;
    case '0':
      statusText = '退回';
      break;
    default:
      statusText = '修改状态';
  }

  proxy.$confirm(`是否确认${statusText}选中的${ids.value.length}条数据项？`, "警告", {
    confirmButtonText: proxy.$t('common.ok'),
    cancelButtonText: proxy.$t('common.cancel'),
    type: "warning"
  }).then(async function () {
    try {
      // Create an array of promises for updating each selected item
      const updatePromises = ids.value.map(id => {
        return getEgFeedbackMain(id).then(res => {
          if (res.code == 200) {
            const updateData = { ...res.data, isStaus: status };
            return updateEgFeedbackMain(updateData);
          }
        });
      });
      
      await Promise.all(updatePromises);
      
      proxy.$modal.msgSuccess(`${statusText}成功`);
      getList();
    } catch (error) {
      console.error(error);
      proxy.$modal.msgError(`${statusText}失败`);
    }
  }).catch(() => {
    proxy.$modal.msgInfo("已取消操作");
  });
}

// 删除按钮操作
function handleDelete(row) {
  const Ids = row.feedbackID || ids.value

  proxy
    .$confirm('是否确认删除参数编号为"' + Ids + '"的数据项？', "警告", {
      confirmButtonText: proxy.$t('common.ok'),
      cancelButtonText: proxy.$t('common.cancel'),
      type: "warning",
    })
    .then(function () {
      return delEgFeedbackMain(Ids)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess("删除成功")
    })
}

function  SelectMachine() {
  if (form.value.machineNo !="") {
    var queryParams = {
      pageNum: 1,
      pageSize: 10,
      HZJQBH: form.value.machineNo,
    }
    listsaleorder(queryParams).then((res) => {
      if (res.data.result.length > 0) { 
        var selectedData = res.data.result[0]
        form.value.machineNo = selectedData.hzjqbh || ''
        form.value.orderNo = selectedData.hzorder || ''
        form.value.cusNo = selectedData.cust || ''
        form.value.cusName = selectedData.cname || ''
        form.value.ProblemModel = selectedData.spec || ''
        form.value.shipmentDate = selectedData.sDate || ''
        form.value.factoryDate = selectedData.dlvdate || ''
      }
  })
    // Populate form fields with selected machine data
   
    // Add any other fields you want to populate from the selected machine
  } 
}
// 机器选择器回调函数
function handleSelectMachine(selectedData) {
  if (selectedData) {
    // Populate form fields with selected machine data
    form.value.machineNo = selectedData.hzjqbh || ''
    form.value.orderNo = selectedData.hzorder || ''
    form.value.cusNo = selectedData.cust || ''
    form.value.cusName = selectedData.cname || ''
    form.value.ProblemModel = selectedData.spec || ''
    form.value.shipmentDate = selectedData.sDate || ''
    form.value.factoryDate = selectedData.dlvdate || ''

    // Add any other fields you want to populate from the selected machine
  } 
}
// 供应商选择器回调函数
function handleSelectSupp(selectedData) {
  if (selectedData) {
    // Populate form fields with selected supplier data
    form.value.suppNo = selectedData.code || ''
    form.value.suppName = selectedData.cname || ''
    // Add any other fields you want to populate from the selected supplier
  }
  getList()
}
// 客户选择器回调函数
function handleSelectCus(selectedData) {
  if (selectedData) {
    // Populate form fields with selected customer data
    form.value.cusNo = selectedData.code || ''
    form.value.cusName = selectedData.cname || ''
    // Add any other fields you want to populate from the selected customer
  }
  getList()
}
//获取问题类型选项 
proxy.getDicts('sys_fb_qusetiontype').then((response) => {
   problemTypeOptions.value = response.data
})

// 对话按钮操作
function handleChat(feedbackID) {
  router.push({
    path: '/fb/EgFeedbackList',
    query: { feedbackID: feedbackID }
  });
}

handleQuery()
</script>